package com.example.sonny.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;

import com.example.sonny.Constraint;
import com.example.sonny.bean.BookItem;
import com.example.sonny.bean.PageBean;
import com.example.sonny.dutest.BookDetailActivity;
import com.example.sonny.dutest.MenuActivity;
import com.example.sonny.dutest.PublishBookActivity;
import com.example.sonny.dutest.R;
import com.example.sonny.dutest.SingleBookActivity;
import com.example.sonny.dutest.demoData;
import com.example.sonny.util.AsyncHttpClientUtil;
import com.example.sonny.util.adapter.BookGridAdapter;
import com.example.sonny.util.adapter.BookListAdapter;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array;
import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link myBookFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link myBookFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class myBookFragment extends Fragment   implements AbsListView.OnItemClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private int mParam1;

    private OnFragmentInteractionListener mListener;

    /**
     * The fragment's ListView/GridView.
     */
    private AbsListView mListView;
    private AbsListView mGridView;
    private Button btn_publish_book;

    /**
     * The Adapter which will be used to populate the ListView/GridView with
     * Views.
     */
    private BookGridAdapter mAdapter;
    private BookGridAdapter mAdapter1;

    private ArrayList<BookItem> books;
    private ArrayList<BookItem> borrows;

    private BookItem book;
    private PageBean page;
    private PageBean page1;
    // TODO: Rename and change types and number of parameters
    public static myBookFragment newInstance(int param1) {
        myBookFragment fragment = new myBookFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    public myBookFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getInt(ARG_PARAM1);
        }

        page = new PageBean();
        page1 = new PageBean();
        getData();
       // getMyBookJob(page.getPage_index());
       // getMyBorrowJob(page1.getPage_index());
       // mAdapter = new BookGridAdapter(getActivity(),books);
    }

    private void getMyBorrowJob(int p){
        AsyncHttpClient client = AsyncHttpClientUtil.getInstence();
        String action = "api/borrowbook";
        RequestParams requestParams = new RequestParams();
        requestParams.add("page", Integer.toString(p));
        client.get(Constraint.API_URL + action, requestParams, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    JSONObject page_obj = response.getJSONObject("page");
                    page1.setPage_index(page_obj.getInt("page_index"));
                    page1.setHas_next(page_obj.getBoolean("has_next"));
                    page1.setHas_previous(page_obj.getBoolean("has_previous"));
                    page1.setItem_count(page_obj.getInt("item_count"));
                    page1.setPage_count(page_obj.getInt("page_count"));
                    if (page1.getPage_index() == 1) {
                        borrows.clear();
                    }
                    JSONArray array = response.getJSONArray("books");
                    for (int i = 0; i < array.length(); i++) {
                        book = new BookItem();
                        book.setName(array.getJSONObject(i).getString("name"));
                        book.setCreated_at(Double.parseDouble(array.getJSONObject(i).getString("created_at")));
                        book.setId(array.getJSONObject(i).getString("id"));
                        book.setImgUrl(array.getJSONObject(i).getString("imgUrl"));
                        book.setIntro(array.getJSONObject(i).getString("intro"));
                        book.setLend_id(array.getJSONObject(i).getString("lend_id"));
                        book.setState(Integer.parseInt(array.getJSONObject(i).getString("state")));
                        book.setUser_id(array.getJSONObject(i).getString("user_id"));
                        book.setUser_image(array.getJSONObject(i).getString("user_image"));
                        book.setUser_name(array.getJSONObject(i).getString("user_name"));
                        borrows.add(book);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mAdapter1 = new BookGridAdapter(getActivity(), borrows);
                ((AdapterView<ListAdapter>) mGridView).setAdapter(mAdapter1);
                // Set OnItemClickListener so we can be notified on item clicks
                //progressDialog.cancel();

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                Log.e("exbook error", Integer.toString(statusCode));
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_my_book, container, false);
        // Set the adapter
        mListView = (AbsListView) view.findViewById(R.id.myBook_gv);
        mGridView = (AbsListView) view.findViewById(R.id.my_borrow_gv);
        btn_publish_book = (Button)view.findViewById(R.id.btn_publish_book);

        // Set OnItemClickListener so we can be notified on item clicks
        mListView.setOnItemClickListener(this);
        mGridView.setOnItemClickListener(this);
        btn_publish_book.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), PublishBookActivity.class);
                startActivity(intent);
            }
        });

        mAdapter = new BookGridAdapter(getActivity(), books);
        mAdapter1 = new BookGridAdapter(getActivity(), borrows);
        ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
        ((AdapterView<ListAdapter>) mGridView).setAdapter(mAdapter1);

        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

  /*  @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            ((MenuActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_PARAM1));
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }*/

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        if(view.getId()==R.id.myBook_gv){
            bundle.putSerializable("book",books.get(position));
        }else{
            bundle.putSerializable("book",borrows.get(position));
        }

        intent.putExtras(bundle);
        intent.setClass(getActivity(),BookDetailActivity.class);
        startActivity(intent);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    private void getData(){
        demoData demo = new demoData();
        demo.initData();
        books = demo.getBooks();
        borrows =demo.getBooks();
    }

    private void getMyBookJob(int p){
        AsyncHttpClient client = AsyncHttpClientUtil.getInstence();
        String action = "api/mybook";
        RequestParams requestParams = new RequestParams();
        requestParams.add("page",Integer.toString(p));
        client.get(Constraint.API_URL + action, requestParams, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    JSONObject page_obj = response.getJSONObject("page");
                    page.setPage_index(page_obj.getInt("page_index"));
                    page.setHas_next(page_obj.getBoolean("has_next"));
                    page.setHas_previous(page_obj.getBoolean("has_previous"));
                    page.setItem_count(page_obj.getInt("item_count"));
                    page.setPage_count(page_obj.getInt("page_count"));
                    if (page.getPage_index() == 1) {
                        books.clear();
                    }
                    JSONArray array = response.getJSONArray("books");
                    for (int i = 0; i < array.length(); i++) {
                        book = new BookItem();
                        book.setName(array.getJSONObject(i).getString("name"));
                        book.setCreated_at(Double.parseDouble(array.getJSONObject(i).getString("created_at")));
                        book.setId(array.getJSONObject(i).getString("id"));
                        book.setImgUrl(array.getJSONObject(i).getString("imgUrl"));
                        book.setIntro(array.getJSONObject(i).getString("intro"));
                        book.setLend_id(array.getJSONObject(i).getString("lend_id"));
                        book.setState(Integer.parseInt(array.getJSONObject(i).getString("state")));
                        book.setUser_id(array.getJSONObject(i).getString("user_id"));
                        book.setUser_image(array.getJSONObject(i).getString("user_image"));
                        book.setUser_name(array.getJSONObject(i).getString("user_name"));
                        books.add(book);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mAdapter = new BookGridAdapter(getActivity(), books);
                ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
                // Set OnItemClickListener so we can be notified on item clicks
                //progressDialog.cancel();

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                Log.e("exbook error", Integer.toString(statusCode));
            }
        });
    }
}
